package com.tanhua.dubbo.es.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.UserLocation;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.*;

import java.util.HashMap;
import java.util.Map;

import static java.lang.String.valueOf;

@Service(version = "1.0.0")
@Slf4j
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    public void initIndex() {
        if (!elasticsearchTemplate.indexExists("tanhua")) {
            elasticsearchTemplate.createIndex(UserLocation.class);
        }
        if (!elasticsearchTemplate.typeExists("tanhua", "user_location")) {
            elasticsearchTemplate.putMapping(UserLocation.class);
        }
    }

    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {

        try {
            GetQuery getQuery = new GetQuery();
            getQuery.setId(valueOf(userId));
            UserLocation userLocation = elasticsearchTemplate.queryForObject(getQuery, UserLocation.class);
            if (ObjectUtil.isEmpty(userLocation)) {
                userLocation.setAddress(address);
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setUpdated(userLocation.getCreated());
                userLocation.setUserId(userId);
                userLocation.setLastUpdated(userLocation.getCreated());
                userLocation.setLocation(new GeoPoint(latitude, longitude));
                IndexQuery query = new IndexQueryBuilder().withObject(userLocation).build();
                elasticsearchTemplate.index(query);
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("location", new GeoPoint(latitude, longitude));
                map.put("updated", System.currentTimeMillis());
                map.put("lastUpdated", userLocation.getUpdated());
                map.put("address", address);
                UpdateRequest updateRequest = new UpdateRequest();
                updateRequest.doc(map);
                UpdateQuery query = new UpdateQueryBuilder().withId(String.valueOf(userId))
                        .withUpdateRequest(updateRequest)
                        .withClass(UserLocation.class)
                        .build();
                elasticsearchTemplate.update(query);
            }

        } catch (Exception e) {
            log.error("更新地理位置失败~ userId = " + userId + ", longitude = " + longitude + ", latitude = " + latitude + ", address = " + address, e);
        }
        return false;
    }

    @Override
    public UserLocationVo queryByUserId(Long userId) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(String.valueOf(userId));
        UserLocation userLocation = elasticsearchTemplate.queryForObject(getQuery, UserLocation.class);
        if (ObjectUtil.isNotEmpty(userLocation)) {
            return UserLocationVo.format(userLocation);
        }
        return null;
    }

    @Override
    public PageInfo<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude, Double distance, Integer page, Integer pageSize) {
        PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        String fieldName = "location";
        //分页
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        searchQueryBuilder.withPageable(pageRequest);
        //限制距离
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        GeoDistanceQueryBuilder geoDistanceQueryBuilder = new GeoDistanceQueryBuilder(fieldName);
        geoDistanceQueryBuilder.point(new GeoPoint(latitude,longitude));
        geoDistanceQueryBuilder.distance(distance / 1000, DistanceUnit.KILOMETERS);
        boolQueryBuilder.must(geoDistanceQueryBuilder);
        searchQueryBuilder.withQuery(boolQueryBuilder);
        //顺序
        GeoDistanceSortBuilder geoDistanceSortBuilder = new GeoDistanceSortBuilder(fieldName, latitude, longitude);
        geoDistanceSortBuilder.order(SortOrder.ASC);
        geoDistanceSortBuilder.unit(DistanceUnit.KILOMETERS);
        searchQueryBuilder.withSort(geoDistanceSortBuilder);


        AggregatedPage<UserLocation> aggregatedPage = elasticsearchTemplate.queryForPage(searchQueryBuilder.build(), UserLocation.class);
        if (CollUtil.isEmpty(aggregatedPage)) {
            return null;
        }

        pageInfo.setRecords(UserLocationVo.formatToList(aggregatedPage.getContent()));
        return pageInfo;
    }
}
